/**
 * uploadImg 1.0.0
 * author: lizhien
 * released on: 2017-05-15
 */

$.fn.extend({
	uploadImg: function (imgWidth, imgHeight, uploadUrl, callback, param) {
		var jcropContainer;
		var screenWidth;
		var realWidth;
		var realHeight;
		var screenWidth = $(window).width();
		var screenHeight = $(window).height();
		var that = $(this);
		that.change(function (evt) {
			var file = evt.dataTransfer !== undefined ? evt.dataTransfer.files[0] : evt.target.files[0];
			var html = '\
				<div id="uploadContainer" style="display:block;position:fixed;left:0;top:0;width:100%;height:100%;overflow:hidden;background:#fff;z-index:20000;">\
				<div style="height:2.4rem;line-height:2.4rem;text-align:center;color:#333;padding:0;">\
				<a id="btnCancel" style="float:left;line-height:2.4rem;height:2.4rem;width:2.4rem;"><i style="margin-top:.8rem;display:inline-block;-webkit-transform: rotate(225deg);height:.5rem;width:.5rem;border-width: 2px 2px 0 0;border-color: #3cb1ff;border-style: solid;"></i></a>\
				<span style="font-size:1rem;">选取图片尺寸</span>\
				<a id="btnSave" style="float:right;line-height:2.4rem;height:2.4rem;width:3rem;background:#fff;">保存</a>\
				</div>\
				<img id="uploadImg" style="width: 100%;"><br>\
				<canvas id="myCanvas" style="display:none"></canvas>\
				</div>';
			$('body').append(html);

			var reader = new FileReader();
			reader.onload = function (e) {
				$("<img/>").attr("src", e.target.result).load(function () {
					realWidth = this.width;
					realHeight = this.height;
					// console.log("width:" + realWidth + 'px' + ";height:" + realHeight + 'px');

					//修复ios旋转问题 lizhien 20170517
					var imgObj = this;
					if (navigator.userAgent.match(/iphone/i)) {
						EXIF.getData(file, function () {
							var canvas = document.getElementById("myCanvas");
							var orientation = EXIF.getTag(this, 'Orientation');
							var base64 = e.target.result;

							//开始旋转
							switch (orientation) {
							case 6: //需要顺时针90度旋转
								console.log('需要顺时针90度旋转');
								rotateImg(imgObj, canvas, 1);
								base64 = canvas.toDataURL("image/jpeg");
								realWidth = imgObj.height;
								realHeight = imgObj.width;
								break;
							case 3: //需要180度旋转
								console.log('需要180度旋转');
								rotateImg(imgObj, canvas, 2);
								base64 = canvas.toDataURL("image/jpeg");
								break;
							case 8: //需要逆时针90度旋转
								console.log('需要逆时针90度旋转');
								rotateImg(imgObj, canvas, 3);
								base64 = canvas.toDataURL("image/jpeg");
								realWidth = imgObj.height;
								realHeight = imgObj.width;
								break;
							}

							$("#uploadImg").attr('src', base64);
						});
					} else {
						$("#uploadImg").attr('src', e.target.result);
					}

					$('#uploadImg').load(function () {
						var rate = screenWidth / realWidth;
						var imgRate = imgWidth / imgHeight;
						var realRate = realWidth / realHeight;
						if (realRate < imgRate) {
							var nowWidth = realWidth;
							var nowHeight = nowWidth * imgHeight / imgWidth;
							var leftMargin = 0;
							var topMargin = (realHeight - nowHeight - 100) / 2;
						} else {
							var nowHeight = realHeight;
							var nowWidth = nowHeight * imgWidth / imgHeight;
							var leftMargin = (realWidth - nowWidth) / 2;
							var topMargin = 0;
						}
						// console.log(screenWidth + ':' + rate + ':' + leftMargin + ':' + topMargin + ':' + nowWidth + ':' + nowHeight);

						$('#uploadImg').Jcrop({
							bgOpacity: 0.3,
							setSelect: [leftMargin * rate, topMargin * rate, (nowWidth + leftMargin) * rate, (nowHeight + topMargin) * rate],
							aspectRatio: imgWidth / imgHeight,
							onSelect: function imgSelect(container) {
								jcropContainer = container;
							}
						});
					});
				});
			};
			reader.readAsDataURL(file);

			$('#btnCancel').click(function () {
				$('#uploadContainer').remove();
				that.val('');
			});

			$('#btnSave').click(function () {
				$.showLoading();
				var can = document.getElementById("myCanvas");
				var ctx = can.getContext("2d");
				var img = document.getElementById("uploadImg");
				var canWidth = can.width = imgWidth;
				var canHeight = can.height = imgHeight;
				var rate = realWidth / screenWidth;
				var newX = jcropContainer.x * rate;
				var newY = jcropContainer.y * rate;
				var newW = jcropContainer.w * rate;
				var newH = jcropContainer.h * rate;
				ctx.drawImage(img, newX, newY, newW, newH, 0, 0, canWidth, canHeight);

				var base64Data = can.toDataURL("image/jpeg");
				var bytes = window.atob(base64Data.split(',')[1]);
				var ab = new ArrayBuffer(bytes.length);
				var ia = new Uint8Array(ab);
				for (var i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i);
				}
				base64Data = new Blob([ab], {
						type: 'image/jpeg',
						endings: 'transparent'
					});

				var fd = new FormData();
				fd.append('image', base64Data, 'upload' + (new Date().getTime()) + '.jpg');
                // fd.append('image_type', SCOPE.upload_img_type);
				if (param) {
					for (var i in param) {
						fd.append(i, param[i]);
					}
				}
				$.ajax({
					url: uploadUrl,
					type: "post",
					data: fd,
					dataType: 'json',
					processData: false, // 必须
					contentType: false, // 必须
					success: function (d) {
						$.hideLoading();
						// console.log(d);
						callback(d);
						$('#uploadContainer').remove();
						that.val('');
					}
				});
			});
		});
	},
	uploadAvatar: function (callback, param) {
		if (!param)
			param = {
				'type': 'avatar'
			};
		return $(this).uploadImg(300, 300, SCOPE.upload_img_url, callback, param);
	},
	uploadCard: function (callback, param) {
		if (!param)
			param = {
				'type': 'card'
			};
		return $(this).uploadImg(500, 300, SCOPE.upload_img_url, callback, param);
	},
	uploadPic: function (callback, param) {
		if (!param)
			param = {
				'type': 'picture'
			};
		return $(this).uploadImg(800, 600, SCOPE.upload_img_url, callback, param);
	},
	uploadPho: function (callback, param) {
		if (!param)
			param = {
				'type': 'photo'
			};
		return $(this).uploadImg(600, 800, SCOPE.upload_img_url, callback, param);
	}
});

$(function () {
    /**
     * 保存被点击的上传元素对象
     */
    $('#uploaderInput').click(function () {
        SCOPE.upload_img_obj = $(this);
		if ($("#uploaderFiles").find('li').length >= SCOPE.upload_img_max_num) {
			$.toptip('最多上传'+ SCOPE.upload_img_max_num +'张图片', 'error');
			return false;
		}
    });

    /**
     * 上传成功 回调函数
     */
    $('#uploaderInput').uploadAvatar(function (d) {
        var _field = SCOPE.upload_img_obj.data('field');
        if (d.code != 200) {
            $.toptip(d.msg, 'error');
        } else {
			$("#uploaderFiles").append('<li class="weui-uploader__file" style="background-image:url('+ d.data[0].host_path +')"></li>');
            SCOPE.upload_img_obj.after('<input type="hidden" name="image_' + $("#uploaderFiles").find('li').length +'" value="'+ d.data[0].path +'" />');
        }
        setTimeout(function () {
            $(".weui_loading_toast").remove();
        }, 888);

    });
});

//对图片旋转处理
function rotateImg(img, canvas, step) {
	var width = img.width;
	var height = img.height;
	var step = step || 0;
	var degree = step * 90 * Math.PI / 180;
	var ctx = canvas.getContext('2d');
	// console.log('step:' + step);
	switch (step) {
	case 0: //初始状态
		canvas.width = width;
		canvas.height = height;
		ctx.drawImage(img, 0, 0);
		break;
	case 1: //顺时针90
		canvas.width = height;
		canvas.height = width;
		ctx.rotate(degree);
		ctx.drawImage(img, 0, -height);
		break;
	case 2: //旋转180
		canvas.width = width;
		canvas.height = height;
		ctx.rotate(degree);
		ctx.drawImage(img, -width, -height);
		break;
	case 3: //逆时针90
		canvas.width = height;
		canvas.height = width;
		ctx.rotate(degree);
		ctx.drawImage(img, -width, 0);
		break;
	}
}

// demo
// $(function () {
// $('#avatarFile').uploadImg(300, 300, 'http://192.168.0.8/mobom2/public/home/base/get_upload_img.html', function (d) {
// $('#avatarImg').attr('src', d.data.host_path);
// }, {
// 'type': 'avatar'
// });
// });
